#include "memberoperationdetails.h"
#include "ui_memberoperationdetails.h"
#include <QDateTime>
#include <QKeyEvent>
#include <QDebug>
#include <QMessageBox>
#include "inquiresql.h"
#include "calendar.h"

MemberOperationDetails::MemberOperationDetails(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MemberOperationDetails)
{
    ui->setupUi(this);
    this->setLayout(ui->MainLayout);

    //设置自定义的鼠标指针图案
    QCursor *myCursor= new QCursor(QPixmap(":/Mouse/Image/mouse/mouse.png"),15,10);
    setCursor(*myCursor);

    QHeaderView* vheaderView = ui->tableWidgetMemberOperationDetail->verticalHeader();
    vheaderView->setHidden(true);

//    ui->tableWidgetPurchaseOrderForm->setColumnWidth(0,110);
//    ui->tableWidgetPurchaseOrderForm->setColumnWidth(1,150);
//    ui->tableWidgetPurchaseOrderForm->setColumnWidth(2,200);
//    ui->tableWidgetPurchaseOrderForm->setColumnWidth(3,100);
//    ui->tableWidgetPurchaseOrderForm->setColumnWidth(4,200);

    setQtableWidgetHeaderStyle();

    ui->lineEditDateStart->installEventFilter(this);
    ui->lineEditDateEnd->installEventFilter(this);

    m_calendar = new Calendar(this);
    m_calendar->hide();

    connect(m_calendar, SIGNAL(signalUpdateLineEditDate(QString)),
            this, SLOT(slotUpdateLineEditDate(QString)));

    m_LineEdit = -1;
    LineEditEnable = true;

    //初始化显示当天的进货订单
    initLineEditTime();
}

MemberOperationDetails::~MemberOperationDetails()
{
    delete ui;
}

bool MemberOperationDetails::eventFilter(QObject *target, QEvent *event)
{
    if ( target == ui->lineEditDateEnd || target == ui->lineEditDateStart )
    {
        //鼠标左键释放事件
        if (event->type() == QEvent::MouseButtonRelease)
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
            if (mouseEvent->button() == Qt::LeftButton)
            {
                QString time;
                if (target == ui->lineEditDateEnd)
                {
                    m_LineEdit = end;
                    time = ui->lineEditDateEnd->text();
                }
                else if (target == ui->lineEditDateStart)
                {
                    m_LineEdit = start;
                    time = ui->lineEditDateStart->text();
                }
                if (LineEditEnable)
                {
                    m_calendar->setSelectedCurrentDate(time);
                    m_calendar->setWindowFlags(
                                Qt::FramelessWindowHint | Qt::Dialog);

                    if (m_LineEdit == start)
                    {
                        QPoint GlobalPoint(ui->lineEditDateStart->mapToGlobal(QPoint(0, 0)));
                        int x = GlobalPoint.x();
                        int y = GlobalPoint.y();
                        m_calendar->setGeometry(x , y + 35, 150, 130);
                    }
                    else if (m_LineEdit == end)
                    {
                        QPoint GlobalPoint(ui->lineEditDateEnd->mapToGlobal(QPoint(0, 0)));
                        int x = GlobalPoint.x();
                        int y = GlobalPoint.y();
                        m_calendar->setGeometry(x , y + 35, 150, 130);
                    }
                    m_calendar->show();
                }
            }
        }
    }
    return QWidget::eventFilter(target, event);
}

void MemberOperationDetails::displayTableWidgetMemberOperationDetails()
{
    m_list.clear();
    ui->tableWidgetMemberOperationDetail->clear();

    if (LineEditEnable)
        m_list = m_sql->InquireMemberOperationDetails(ui->lineEditDateStart->text(),
                        ui->lineEditDateEnd->text(),
                        ui->comboBoxInquireManner->currentIndex(),
                        ui->lineEditInquireInformation->text());
    else
        m_list = m_sql->InquireMemberOperationDetails("all", "all",
                        ui->comboBoxInquireManner->currentIndex(),
                        ui->lineEditInquireInformation->text());

    setQtableWidgetHeaderStyle();

    //显示会员办卡/充值信息
    ui->tableWidgetMemberOperationDetail->setRowCount(m_list.count());

    for(int i = 0; i < m_list.count(); ++i)
    {
        QTableWidgetItem *memberID      = new QTableWidgetItem(
                    m_list.at(i).get_personID());
        QTableWidgetItem *memberName         = new QTableWidgetItem(
                    m_list.at(i).get_personName());
        QTableWidgetItem *memberLevel              = new QTableWidgetItem(
                    m_list.at(i).get_memberLevel());
        QTableWidgetItem *consumptionType        = new QTableWidgetItem(
                    m_list.at(i).get_consumptionType());
        QTableWidgetItem *consumptionTotal                 = new QTableWidgetItem(
                    completionPrice(m_list.at(i).get_consumptionTotal()));
        QTableWidgetItem *integration      = new QTableWidgetItem(
                    m_list.at(i).get_integration());
        QTableWidgetItem *cashPayment         = new QTableWidgetItem(
                    completionPrice(m_list.at(i).get_cashPayment()));
        QTableWidgetItem *cupPayment              = new QTableWidgetItem(
                    completionPrice(m_list.at(i).get_cupPayment()));
        QTableWidgetItem *staffName        = new QTableWidgetItem(
                    m_list.at(i).get_staffName());
        QTableWidgetItem *consumptionDate                 = new QTableWidgetItem(
                    m_list.at(i).get_consumptionDate());

        //设置对齐方式
        memberID->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        memberLevel->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        consumptionType->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        consumptionTotal->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter );
        integration->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        cashPayment->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter );
        cupPayment->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter );
        staffName->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        consumptionDate->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );

        memberID->setFont(QFont("DejaVu Sans", 11, 2, false));
        memberName->setFont(QFont("DejaVu Sans", 11, 2, false));
        memberLevel->setFont(QFont("DejaVu Sans", 11, 2, false));
        consumptionType->setFont(QFont("DejaVu Sans", 11, 2, false));
        consumptionTotal->setFont(QFont("DejaVu Sans", 11, 2, false));
        integration->setFont(QFont("DejaVu Sans", 11, 2, false));
        cashPayment->setFont(QFont("DejaVu Sans", 11, 2, false));
        cupPayment->setFont(QFont("DejaVu Sans", 11, 2, false));
        staffName->setFont(QFont("DejaVu Sans", 11, 2, false));
        consumptionDate->setFont(QFont("DejaVu Sans", 11, 2, false));

        ui->tableWidgetMemberOperationDetail->setItem(i, 0, memberID);
        ui->tableWidgetMemberOperationDetail->setItem(i, 1, memberName);
        ui->tableWidgetMemberOperationDetail->setItem(i, 2, memberLevel);
        ui->tableWidgetMemberOperationDetail->setItem(i, 3, consumptionType);
        ui->tableWidgetMemberOperationDetail->setItem(i, 4, consumptionTotal);
        ui->tableWidgetMemberOperationDetail->setItem(i, 5, integration);
        ui->tableWidgetMemberOperationDetail->setItem(i, 6, cashPayment);
        ui->tableWidgetMemberOperationDetail->setItem(i, 7, cupPayment);
        ui->tableWidgetMemberOperationDetail->setItem(i, 8, staffName);
        ui->tableWidgetMemberOperationDetail->setItem(i, 9, consumptionDate);
    }

    ui->tableWidgetMemberOperationDetail->setCurrentItem(
                ui->tableWidgetMemberOperationDetail->item(m_list.count() - 1, 0));

    setTableWidgetColor();

    //显示会员操作统计
    QStringList memberOperationDetailStatistics;
    if (LineEditEnable)
        memberOperationDetailStatistics
            = m_sql->MemberOperationDetailsStatistics(
                tr("会员办卡"), tr("会员充值"),
                ui->lineEditDateStart->text(), ui->lineEditDateEnd->text(),
                ui->comboBoxInquireManner->currentIndex(),
                ui->lineEditInquireInformation->text());
    else
        memberOperationDetailStatistics
            = m_sql->MemberOperationDetailsStatistics(
                tr("会员办卡"), tr("会员充值"),
                "all", "all",
                ui->comboBoxInquireManner->currentIndex(),
                ui->lineEditInquireInformation->text());

    ui->QLabelHandleResult->setText(completionPrice(memberOperationDetailStatistics.at(0)));
    ui->QLabelRechargeResult->setText(completionPrice(memberOperationDetailStatistics.at(1)));
}


void MemberOperationDetails::initLineEditTime()
{
    ui->lineEditDateStart->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd"));
    ui->lineEditDateEnd->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd"));
    ui->tableWidgetMemberOperationDetail->clear();
    ui->tableWidgetMemberOperationDetail->setRowCount(0);

    setQtableWidgetHeaderStyle();
}

void MemberOperationDetails::slotUpdateLineEditDate(QString date)
{
    if (m_LineEdit == start)
    {
        ui->lineEditDateStart->setText(date);
        return;
    }
    if (m_LineEdit == end)
    {
        ui->lineEditDateEnd->setText(date);
        return;
    }
}

void MemberOperationDetails::on_pushButtonInquire_clicked()
{
    int startYear = ui->lineEditDateStart->text().mid(0, 4).toInt();
    int startMonth = ui->lineEditDateStart->text().mid(5, 2).toInt();
    int startDay = ui->lineEditDateStart->text().mid(8, 2).toInt();

    int endYear = ui->lineEditDateEnd->text().mid(0, 4).toInt();
    int endMonth = ui->lineEditDateEnd->text().mid(5, 2).toInt();
    int endDay = ui->lineEditDateEnd->text().mid(8, 2).toInt();

    if ( (startYear > endYear) || (startYear == endYear && startMonth > endMonth)
         || (startYear == endYear && startMonth == endMonth && startDay > endDay) )
    {
        QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."),
                                 tr("\n开始日期大于结束日期，请重新设置") );
    }
    else
    {
        displayTableWidgetMemberOperationDetails();
    }
}

void MemberOperationDetails::setQtableWidgetHeaderStyle()
{
    QStringList headers;
    headers << tr("会员卡号") << tr("会员姓名") << tr("会员等级") << tr("消费类型")
            << tr("消费金额") << tr("积分") << tr("现金支付") << tr("银联支付")
            << tr("服务员工") << tr("消费日期") ;

    ui->tableWidgetMemberOperationDetail->setColumnCount(10);
    ui->tableWidgetMemberOperationDetail->setHorizontalHeaderLabels(headers);

    for (int i = 0; i < 10; ++i)
    {
        ui->tableWidgetMemberOperationDetail
                ->horizontalHeaderItem(i)->setFont(QFont("Helvetica", 12, 2, false));
        ui->tableWidgetMemberOperationDetail
                ->horizontalHeaderItem(i)->setTextColor(QColor(200,111,30));
    }
}

void MemberOperationDetails::setTableWidgetColor()
{
    for (int i = 0; i < ui->tableWidgetMemberOperationDetail->rowCount(); ++i)
    {
        if (i % 2 == 0)
        {
            for (int j = 0; j < ui->tableWidgetMemberOperationDetail->columnCount(); ++j)
            {
                QTableWidgetItem *item = ui->tableWidgetMemberOperationDetail->item(i,j);
                if (item)
                {
                    const QColor color = QColor(252, 222, 156);
                    item->setBackgroundColor(color);
                }
            }
        }
    }
}

QString MemberOperationDetails::completionPrice(const QString &price)
{
    QString number = price;
    if (number.isEmpty() || number.toDouble() == 0)
    {
        number.append("0.00");
        return number;
    }
    if (number.contains(".", Qt::CaseInsensitive))
    {
        if (number.left(1) == ".")
        {
            number.replace(0, 1, "0.");
            return number;
        }
        if (number.right(1) == ".")
        {
            number.append("00");
            return number;
        }
        if (number.right(2).contains(".", Qt::CaseInsensitive))
        {
            number.append("0");
            return number;
        }
    }
    else
    {
        number.append(".00");
        return number;
    }

    return NULL;
}

void MemberOperationDetails::on_comboBox_activated(int index)
{
    QDateTime currentTime = QDateTime::currentDateTime();//获取系统现在的时间
//    QDateTime startTime, endTime;
    QString startTimeString, endTimeString;
    switch (index)
    {
        case 0 :  //今天
            startTimeString = currentTime.toString("yyyy-MM-dd");
            endTimeString = startTimeString;
            break;
        case 1 :  //昨天
            startTimeString = currentTime.addDays(-1).toString("yyyy-MM-dd");
            endTimeString = startTimeString;
            break;
        case 2 :  //本月
            startTimeString = currentTime.toString("yyyy-MM-dd").replace(8, 2, "01");
            endTimeString = currentTime.toString("yyyy-MM-dd");
            break;
        case 3 :  //上月
            startTimeString = currentTime.addMonths(-1).toString("yyyy-MM-dd").replace(8, 2, "01");
            endTimeString = currentTime.addDays(currentTime.toString("d").toInt() * -1)
                    .toString("yyyy-MM-dd");
            break;
        case 4 :  //今年
            startTimeString = currentTime.toString("yyyy-MM-dd").replace(5, 5, "01-01");
            endTimeString = currentTime.toString("yyyy-MM-dd");
            break;
        case 5 :  //去年
            startTimeString = currentTime.addYears(-1).toString("yyyy-MM-dd").replace(5, 5, "01-01");
            endTimeString = currentTime.addYears(-1).toString("yyyy-MM-dd").replace(5, 5, "12-31");
            break;
        case 6 :  //全部
            ui->lineEditDateStart->setText(tr("全部"));
            ui->lineEditDateEnd->setText(tr("全部"));
            ui->lineEditDateStart->setDisabled(true);
            ui->lineEditDateEnd->setDisabled(true);
            LineEditEnable = false;
            return;
        default :
            break;
    }
    ui->lineEditDateStart->setDisabled(false);
    ui->lineEditDateEnd->setDisabled(false);
    LineEditEnable = true;
    ui->lineEditDateStart->setText(startTimeString);
    ui->lineEditDateEnd->setText(endTimeString);
}
